package com.hk.web.domain.lifeCycle.repository;

import com.hk.web.domain.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Created by Antinomy on 16/10/13.
 */

@Repository
public class UserRepository {


    @Value("${hk.schema}")
    private String hkSchema;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired(required = true)
    private JdbcTemplate jdbcTemplate;

    public User findByName(String name) {

        String sql = "select * from " + hkSchema + ".SysUser where closeAccount=0 and name =" + name;

        return getUser(sql);
    }

    public User findByUserId(String userId) {

        String sql = "select * from " + hkSchema + ".SysUser where closeAccount=0 and id =" + userId;

        return getUser(sql);
    }

    private User getUser(String sql) {
        RowMapper rowMapper = new BeanPropertyRowMapper<>(User.class);

        User result = (User) this.jdbcTemplate.queryForObject(sql, rowMapper);

        return result;
    }

    public Integer updatePassword(String name, String password) {

        String sql = "update " + hkSchema + ".SysUser set pwd ='" + password + "' where name =" + name;
        Integer result = this.jdbcTemplate.update(sql);

        return result;
    }
}
